package com.rr.openApi.user.service;

import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
//import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.rr.frame.exception.ServiceException;
import com.rr.frame.utils.UUIDTool;
import com.rr.openApi.user.dao.UserMapper;
import com.rr.md5;
//import com.rr.openApi.user.model.User;
import com.rr.frame.common.JWTHelper;

@Service
public class UserService {
	
   @Autowired
   private UserMapper userMapper;
	
	public Map<String,Object> login(Map<String, Object> paraMap) throws ServiceException,Exception{
		//Map<String, Object> rm = new HashMap<String, Object>();
		
		String username = paraMap.get("username").toString();
		String password = paraMap.get("password").toString();
		
		Map<String, Object> user = userMapper.findUserByUsername(username);
		if(null != user){
			if(password.equals(user.get("password"))){
				 String tokenString = JWTHelper.createJWT(user.get("uid").toString(), user.get("user_name").toString(), 3600 * 3);
				 user.put("token", tokenString);
			}else{
				throw new ServiceException("FA_FALED_USERNAME_PASSWORD_ERROR","账号或密码不正确");
			}
		}else{
			throw new ServiceException("FA_FALED_USER_NOT_EXITS","用户名不存在");
		}
        //User user=null;
		user.remove("password");
        return user;
	}
	
	public Boolean isUserNameExist(Map<String, Object> paraMap) throws ServiceException,Exception{
		
		int count = userMapper.findUsernameCount(paraMap.get("username").toString());
		if(count > 0){
			return false;
		}else{
			return true;
		}
        //User user=null;
       
	}
	
	public String addUser(Map<String, Object> paraMap) throws ServiceException,Exception{
		Map<String, Object> user = new HashMap<String, Object>();
		
		Date date = new Date();  
		Timestamp timestamp = new Timestamp(date.getTime());
		
		String uid = UUIDTool.getUUID();
		user.put("uid", uid);
		user.put("user_name", paraMap.get("username").toString());
		user.put("password", md5.getMD5(paraMap.get("password").toString()));
		user.put("real_name", paraMap.get("realName").toString());
		user.put("add_time", timestamp);
		//md5.getMD5(paraMap.get("password").toString());
		int resultNum = userMapper.signIn(user);
		if(resultNum < 1){
			throw new ServiceException("FA_FAILED_ADD_USER", "用户注册失败");
		}
		
		
		return uid;
	}
}
